package com.cxx.purchasecharge.dal.common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 *
 */
public class IDGenerator
{
    private static Long lastValue = Long.parseLong ("0");
    private static Long lastTimeValue = new Date ().getTime ();
    private static SimpleDateFormat timeFormat = new SimpleDateFormat ("yyMMddHHmmss");

    static
    {
        lastValue = Long.parseLong (timeFormat.format (lastTimeValue));
    }

    public synchronized static long getIdentityID ()
    {
        synchronized (IDGenerator.class)
        {
            synchronized (lastValue)
            {
                synchronized (lastTimeValue)
                {
                    Date curDate = new Date ();
                    long curTimeValue = curDate.getTime ();

                    if (curTimeValue - lastTimeValue < 1000)
                    {
                        return ++lastValue;
                    }
                    else
                    {
                        lastTimeValue = curTimeValue;
                        lastValue = Long.parseLong (timeFormat.format (lastTimeValue));
                        return lastValue;
                    }
                }
            }
        }
    }

    public static String getUUID ()
    {
        return UUID.randomUUID ().toString ();
    }

    public static void main (String[] args)
    {
        /*
         * int j = 1000; while (j > 0) { Thread t = new Thread (new Runnable ()
         * { public void run () { int i = 1000; while (i > 0) { long l =
         * getIdentityID (); System.out.println (l); try { Thread.sleep (1l); }
         * catch (InterruptedException e) { e.printStackTrace (); } i--; } } });
         * t.start (); j--; }
         */
        System.out.println (getIdentityID ());
    }

}
